<?php

// +----------------------------------------------------------------------
// | 版权所有 2017-2027 云南环拓科技有限公司，并保留所有权利。
// +----------------------------------------------------------------------
// | Copyright (c) 2017-2027 http://www.yn123.com All rights reserved.
// +----------------------------------------------------------------------
// | Notice: This code is not open source, it is strictly prohibited
// |         to distribute the copy, otherwise it will pursue its
// |         legal responsibility.
// | 注意：  这不是一个自由软件！您只能在不用于商业目的的前提下对程序代码进行修改和使用,
// |        不允许对程序代码以任何形式任何目的的再发布。
// +----------------------------------------------------------------------
// | Author: feraner <feraner@163.com> 
// | Date: 2019/10/25
// +----------------------------------------------------------------------

namespace app\common\services;
use app\common\facade\Arr;
use app\wechat\service\WechatService;
use think\Db;
use think\facade\Cache;
use think\facade\Config;

/**
 * 微信模版消息发送类
 * Class WechatTemplateService
 * @package app\common\services
 * @author feraner<feraner@163.com>
 * @date 2019/10/25
 */
class WechatTemplateService
{

    /**
     * 跟域名
     * @var null
     */
    protected $baseUrl = null;

    /**
     * @var null 微信模板消息 - ID
     */
    protected $template = null;

    /**
     * 接手消息的用户 openId
     * @var null
     */
    protected $toUser = null;

    /**
     * @var null 微信模板消息 - title
     */
    protected $first = null;

    /**
     * @var null 微信模板消息 - 模板跳转链接
     */
    protected $url = null;

    /**
     * @var null 微信模板消息 - 所需跳转到小程序的具体页面路径，支持带参数,（示例index?foo=bar）
     */
    protected $pagePath = null;

    /**
     * @var null 微信模板消息 - 备注
     */
    protected $remark = null;

    /**
     * @var null 微信模板消息 - 第一行
     */
    protected $keyword1 = null;

    /**
     * @var null 微信模板消息 - 第二行
     */
    protected $keyword2 = null;

    /**
     * @var null 微信模板消息 - 第三行
     */
    protected $keyword3 = null;

    /**
     * @var null 微信模板消息 - 第四行
     */
    protected $keyword4 = null;

    /**
     * @var null 微信模板消息 - 第五行
     */
    protected $keyword5 = null;

    /**
     * @var null 微信模板消息 - 第六行
     */
    protected $keyword6 = null;




    /**
     * WechatTemplateService constructor.
     */
    public function __construct()
    {
        $this->baseUrl = Config::get('api_host_name');
    }

    /**
     * 设置参数
     * @param $key
     * @param $value
     *
     * @return $this
     */
    public function set($key, $value)
    {
        $this->$key = $value;
        return $this;
    }

    /**
     * 获取参数
     * @param $key
     *
     * @return mixed
     */
    public function get($key)
    {
        return $this->$key;
    }


    /**
     * 情况设置的参数
     */
    public function clearSetData()
    {
        $this->set('template', null)
            ->set('first', null)
            ->set('url', null)
            ->set('toUser', null)
            ->set('remark', null)
            ->set('keyword1', null)
            ->set('keyword2', null)
            ->set('keyword3', null)
            ->set('keyword4', null)
            ->set('keyword5', null)
            ->set('keyword6', null)
            ->set('pagePath', null);
        return $this;
    }



    /**
     * 发送微信模版消息
     * @return array
     * @throws \WeChat\Exceptions\InvalidResponseException
     * @throws \WeChat\Exceptions\LocalCacheException
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function send()
    {
        $sendData = [
            'touser'            => $this->toUser,
            'template_id'       => Arr::get($this->getTemplateInfo(), 'template_id', ''),
            'topcolor'          => '#7B68EE',
            'data'              => [
                'first'     => [
                    'value'         => $this->first,
                    'color'         => '#00CD00'
                ],
                'keyword1'  => [
                    'value'         => $this->keyword1,
                    'color'         => '#EE5C42'
                ],
                'remark'    => [
                    'value'         => $this->remark,
                    'color'         => '#030303'
                ]
            ],
        ];
        //设置链接
        if ($this->url) {
            $sendData['url'] = $this->baseUrl . $this->url;
        }
        if ($this->keyword2) {
            $sendData['data']['keyword2'] = [
                'value'         => $this->keyword2,
                'color'         => '#EE9A00'
            ];
        }
        if ($this->keyword3) {
            $sendData['data']['keyword3'] = [
                'value'         => $this->keyword3,
                'color'         => '#EE9A00'
            ];
        }
        if ($this->keyword4) {
            $sendData['data']['keyword4'] = [
                'value'         => $this->keyword4,
                'color'         => '#EE9A00'
            ];
        }
        if ($this->keyword5) {
            $sendData['data']['keyword5'] = [
                'value'         => $this->keyword5,
                'color'         => '#EE9A00'
            ];
        }
        if ($this->keyword6) {
            $sendData['data']['keyword6'] = [
                'value'         => $this->keyword6,
                'color'         => '#EE9A00'
            ];
        }
        try {
            return WechatService::WeChatTemplate()->send($sendData);
        } catch (\Exception $e) {
            //不影响主流程
        }

    }




    /**
     * 获取微信模版消息
     * @param $templateId
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getTemplateInfo()
    {
        $cacheKey = 'wechatTemplate' . $this->template;
        $templateInfo = Cache::get($cacheKey, []);
        if ($this->template && !$templateInfo) {
            $templateInfo = Db::name('wechat_message_tpl')
                ->where('name', $this->template)
                ->field('template_id,name,appid,title')
                ->find() ?: [];
            if ($templateInfo) {
                Cache::set($cacheKey, $templateInfo, 7200);
            }
        }
        return $templateInfo;
    }


    /**
     * 获取代理商审核人员信息
     * @param     $provincesId
     * @param     $cityId
     * @param     $countyId
     * @param int $type 1:兼职审核人员 2：二手商品审核人员
     *
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function getAgencyCheckUsers($provincesId, $cityId, $countyId, $type = 1)
    {
        $agencyInfo = Db::name('system_agent_user')
            ->where('provinces_id', $provincesId)
            ->where('city_id', $cityId)
            ->where('pid', 0)
            ->field('id,job_check_users,market_check_users')
            ->find() ?: [];


        $result = [];
        if (($checkJobUser = Arr::get($agencyInfo, 'job_check_users')) && $type == 1) {
            $checkJobUserArr = array_values(array_filter(explode('|', $checkJobUser)));
            $result['jobCheckUsers'] = Db::name('user')
                ->where('id', 'IN', $checkJobUserArr)
                ->field('id,name,wechat_openid,wechat_unionid')
                ->select() ?: [];
        }
        if (($checkMarketUser = Arr::get($agencyInfo, 'market_check_users')) && $type == 2) {
            $checkMarketUserArr = array_values(array_filter(explode('|', $checkMarketUser)));
            $result['marketCheckUsers'] = Db::name('user')
                ->where('id', 'IN', $checkMarketUserArr)
                ->field('id,name,wechat_openid,wechat_unionid')
                ->select() ?: [];
        }
        return $result;
    }







}
